#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <string>
#include <functional>

class TranslateClient
{
private:
    muduo::net::EventLoopThread _loop; // EventLoopThread对象在实例化完成之后直接就开始监控, 不需要我们自己去启动
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _latch; // 内部使用条件变量进行同步控制
private:
    // 建立连接后的回调, 如果有同步阻塞需要进行唤醒
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected()) 
        {
            _latch.countDown();
            _conn = conn;
        }
        else // 连接关闭
        {
            _conn.reset();
        }
    }
    // 对服务端消息进行处理的回调
    // 这里我们的是翻译服务, 所以只需要打印即可
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer* buf, muduo::Timestamp t)
    {
        std::cout << "响应结果:" << buf->retrieveAllAsString() << std::endl;
    }
    
public:
    TranslateClient(const std::string &sip, int sport) 
    :_client(_loop.startLoop(), muduo::net::InetAddress(sip, sport), "Translateclient"),
    _latch(1)
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this, std::placeholders::_1,
                                    std::placeholders::_2, std::placeholders::_3));
    }
    // 连接服务器
    void connect()
    {
        _client.connect();
        _latch.wait();
    }
    // 发送数据
    bool send(const std::string &msg)
    {
        if(_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }
    
};

int main()
{
    TranslateClient client("127.0.0.1", 8888);
    client.connect(); // 这里需要自己进行同步控制, 等连接建立成功之后再返回
    while(true)
    {
        std::string buf;
        std::cin >> buf;
        client.send(buf);
    }
    return 0;
}